package com.ruoyi.book.controller;

import java.util.List;
import java.util.TimerTask;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.book.util.SpeechSynthesis;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.framework.manager.AsyncManager;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.book.domain.Section;
import com.ruoyi.book.service.ISectionService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 章节Controller
 *
 * @author laoliu
 * @date 2023-05-07
 */
@RestController
@RequestMapping("/book/section")
public class SectionController extends BaseController {
    @Autowired
    private ISectionService sectionService;

    /**
     * 查询章节列表
     */
    @PreAuthorize("@ss.hasPermi('book:section:list')")
    @GetMapping("/list")
    public TableDataInfo list(Section section) {
        startPage();
        List<Section> list = sectionService.selectSectionList(section);
        return getDataTable(list);
    }
    //查询特定小说的章节
    @PreAuthorize("@ss.hasPermi('book:section:list')")
    @GetMapping("/listb/{bookid}")
    public TableDataInfo list2(@PathVariable("bookid") Long bookid,Section section) {
        startPage();
        section.setBookid(bookid);
        List<Section> list = sectionService.selectSectionList(section);
        return getDataTable(list);
    }
    /**
     * 导出章节列表
     */
    @PreAuthorize("@ss.hasPermi('book:section:export')")
    @Log(title = "章节", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, Section section) {
        List<Section> list = sectionService.selectSectionList(section);
        ExcelUtil<Section> util = new ExcelUtil<Section>(Section.class);
        util.exportExcel(response, list, "章节数据");
    }

    /**
     * 获取章节详细信息
     */
    @PreAuthorize("@ss.hasPermi('book:section:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(sectionService.selectSectionById(id));
    }


////    @Autowired
////    ServerConfig serverConfig;
//    @Autowired
//    private  SpeechSynthesis speech;
    /**
     * 新增章节
     */
    @PreAuthorize("@ss.hasPermi('book:section:add')")
    @Log(title = "章节", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody Section section) {
        //>>>AsyncManager.me().execute();
        //section.setAudiourl("地址正在生成，请稍后刷新！");
        int r=sectionService.insertSection(section);
        Long secid = section.getId();
        new Thread(()->{
            Long id=secid;
            try {
                String path = SpeechSynthesis.speech(section.getNcontent(),"book-sec-"+id+".wav");
                System.out.println("finish:"+path);

                //sectionService.updateSection(id,serverConfig.getUrl()+path);
                sectionService.updateSection(id, Constants.RESOURCE_PREFIX+path);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }).start();
        return toAjax(r);
    }

    /**
     * 修改章节
     */
    @PreAuthorize("@ss.hasPermi('book:section:edit')")
    @Log(title = "章节", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Section section) {
        return toAjax(sectionService.updateSection(section));
    }

    /**
     * 删除章节
     */
    @PreAuthorize("@ss.hasPermi('book:section:remove')")
    @Log(title = "章节", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(sectionService.deleteSectionByIds(ids));
    }

    @PreAuthorize("@ss.hasPermi('book:section:audio')")
    @Log(title = "生成音频", businessType = BusinessType.DELETE)
    @GetMapping("/genAudio/{id}")
    public AjaxResult genAudio(@PathVariable("id") Long id){
        Section section = this.sectionService.selectSectionById(id);
        if(section==null){
            return AjaxResult.error("没有这个内容");
        }
//        AsyncManager.me().execute(new TimerTask() {
//            @Override
//            public void run() {
//                Long id1=section.getId();
//                try {
//                    String path = SpeechSynthesis.speech( section.getNcontent(),"book-sec-"+id+".wav");
//                    System.out.println("finish:"+path);
//                    sectionService.updateSection(id1, Constants.RESOURCE_PREFIX+path);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }
//        });
        new Thread(()->{
            Long id1=section.getId();
            try {
                String path = SpeechSynthesis.speech( section.getNcontent(),"book-sec-"+id+".wav");
                System.out.println("finish:"+path);
                sectionService.updateSection(id1, Constants.RESOURCE_PREFIX+path);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }).start();
        return AjaxResult.success("正在生成，请稍后刷新！");
    }
}
